package com.generic.action.member;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.util.ServletContextAware;

import com.generic.dao.impl.ImageDao;
import com.generic.dao.impl.MemberDao;
import com.generic.ds.HibernateSession;
import com.generic.module.impl.Image;
import com.generic.module.impl.Member;
import com.generic.util.Constant;
import com.generic.util.GraphicsUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class PhotoUpload extends ActionSupport implements ServletContextAware {

	private static final long serialVersionUID = -4149403212439528824L;
	private ServletContext servletContext;
	private File[] uploads;
	private String[] uploadFileNames;
	private String[] uploadContentTypes;

	public File[] getUpload() {
		return uploads;
	}

	public String[] getUploadFileName() {
		return uploadFileNames;
	}

	public String[] getUploadContentType() {
		return uploadContentTypes;
	}

	public void setUpload(File[] uploads) {
		this.uploads = uploads;
	}

	public void setUploadFileName(String[] uploadFileNames) {
		this.uploadFileNames = uploadFileNames;
	}

	public void setUploadContentType(String[] uploadContentTypes) {
		this.uploadContentTypes = uploadContentTypes;
	}
	
	@Override
	public void setServletContext(ServletContext context) {
		this.servletContext = context;
	}
	
	public String execute() {		
		return SUCCESS;
	}
	
	@Action(value = "/photo-upload-add", results = {
			@Result(name = "input", location = "photo-upload.jsp"),
		    @Result(name = "success", type="chain", params={"actionName", "photo"}) })
	public String add() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		Member member = (Member)session.get(Constant.SESSION_MEMBER);
		Long memberId = member.getId();
//		Long memberId = 1l;
		HibernateSession hs = new HibernateSession();
		try {
			hs.beginTransaction();
			ImageDao imageDao = new ImageDao(hs);
			
			/* Create directory folder for the image file */
			String dirPath = Constant.IMAGE_PATH + memberId;
			File filePath = new File(servletContext.getRealPath("/") + dirPath);
			filePath.mkdirs();
			
			/* Create directory folder for the image thumbnail */
			dirPath = Constant.IMAGE_THUMB_PATH + memberId;
			File filePath2 = new File(servletContext.getRealPath("/") + dirPath);
			filePath2.mkdirs();
			
			Long seq = imageDao.getMaxId(memberId);
			for (int i = 0; i < uploads.length; i++) {
//				String fileName = uploadFileNames[i].replace(" ", "_");
				String fileExtension = uploadFileNames[i].substring(uploadFileNames[i].lastIndexOf(".")+1);
				String fileName = seq++ + "." + fileExtension;
				File file = new File(filePath, fileName);
				if (!file.exists()) {
					BufferedImage img = ImageIO.read(uploads[i]);
					/* Save image */
					BufferedImage bi = GraphicsUtil.getStandardSize(img);
					ImageIO.write(bi, fileExtension, file);
					
					/* Save image thumbnail */
					file = new File(filePath2, fileName);
					bi = GraphicsUtil.getThumbnailSize(img);
					ImageIO.write(bi, fileExtension, file);
					
					/* Save image meta data into database */
					Image image = new Image();
					image.setProfileId(memberId);
					image.setFileName(fileName);
					imageDao.insertOrUpdate(image);
				}
			}
			/* Set first image as the default image if it hasn't been set */
			if(member.getImageId() == null) {
				Long imageId = imageDao.getMinId(memberId);
				MemberDao memberDao = new MemberDao(hs);
//				memberDao.setDefaultImage(memberId, imageId);
				member.setImageId(imageId);
				memberDao.insertOrUpdate(member);
			}			
			
			hs.commitTransaction();
		} catch (Exception e) {
			hs.rollbackTransaction(e);
		} finally {
			hs.closeSession();
		}

		return SUCCESS;
	}
}
